﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Xml.Linq;
using Microsoft.Xna.Framework.Graphics;

namespace POB
{
	class Unit
	{
		public Vector2			Position		{ get; set; }
		public int				Lives			{ get; set; }
		public List<Component>	Components		{ get; set; }
		public bool				IsLeftTeam		{ get; set; }
		public bool				Dead			{ get; set; }
		public event Touch		IsTouched;
		public event Die		Dies;
        public Vector2 InitialDirection { get; set; }
        public Vector2 InitialPosition { get; set; }

		public Unit (XElement unitElement, World world, Player player, AddOn addOn)
		{
            this.InitialDirection = player.Direction;
            this.InitialPosition = this.Position = player.Position;

			Components = new List<Component>();

			foreach(var xmlComponent in unitElement.Elements())
			{
				if(xmlComponent.Name == "AddOn" && xmlComponent.Attribute("Name").Value == addOn.Name)
				{

				}
				else
				{
                    Type t = Type.GetType("POB.Gameplay.Components." + xmlComponent.Name.LocalName, true);
					Components.Add((Component)Activator.CreateInstance(t, xmlComponent, world, player, this));
				}
			}
		}

		public void Update(float time)
		{
			foreach(Component component in Components)
			{
				component.Update(time);
			}
		}

		public void Draw(float time, SpriteBatch spriteBatch, Matrix matrix)
		{
			matrix  = Matrix.CreateTranslation(new Vector3(Position, 0f)) * matrix;

			foreach(Component component in Components)
			{
				component.Draw(time, spriteBatch, matrix);
			}
		}

		public void Touch(Unit unit)
		{
			if(IsTouched != null)
			{
				IsTouched(unit);
			}

			Lives -= unit.Lives;

			if(Lives <= 0)
			{
				Dead = true;
				if(Dies != null)
				{
					Dies(unit);
				}
			}
		}
	}
}
